import { configStore } from '@/utils/store/configStore'
import { IMPORT_FROM_YAPI_PAGE_KEY, store } from '@/utils/store/store'
import { openHomeTab } from '@/utils/toHomeTab'
import { onMessage } from 'webext-bridge/background'
import { getMockResult, matchRequest } from './matchRequest'

export default defineBackground(() => {
    // 获取配置
    onMessage('getConfig', async () => {
        const config = await configStore.getValue()
        return config
    })

    // 从Yapi导入
    onMessage('importFromYapiPage', async (msg) => {
        await store.set(IMPORT_FROM_YAPI_PAGE_KEY, msg.data)
        openHomeTab()
    })

    // 通信
    onMessage('beforeRequest', async (msg) => {
        // 先看一下插件配置，插件是否启动
        const config = await configStore.getValue()
        if (!config?.enabled) {
            return
        }
        const requestData = msg.data
        // 筛选所有enabled，并且url匹配的项
        const matchedItem = await matchRequest(requestData)
        if (!matchedItem) {
            return
        }
        const mockResult = await getMockResult(matchedItem, requestData)
        if (!mockResult) {
            return
        }
        return {
            matchedUrl: matchedItem?.url,
            ...mockResult,
        }
    })
})
